import { fontToThreeJSON } from './font2hreejson.js';
import { FontLoader } from 'three/addons/loaders/FontLoader.js';

import UI from './gui-system.js'
import opentype from './opentype.js';
const simplifyFont = (ligatureGlyphs, font) => {
  // 修复连字路径闭合

  ligatureGlyphs.forEach((char) => {
    const glyph = font.glyphs[char];
    if (glyph) {
      glyph.path.autoClose = true;
      // 合并重叠控制点（关键！）
      glyph.path = simplifyPath(glyph.path, 0.1); // 简化容差0.1
    }
  });
  return font;
}

// 路径简化算法
function simplifyPath(path, tolerance) {
  const simplified = new Path();
  path.subPaths.forEach((subPath) => {
    const points = subPath.getPoints().map(p => [p.x, p.y]);
    const simplifiedPoints = simplify(points, tolerance); // 使用简化库
    simplified.moveTo(simplifiedPoints[0][0], simplifiedPoints[0][1]);
    simplifiedPoints.slice(1).forEach(p => {
      simplified.lineTo(p[0], p[1]);
    });
  });
  return simplified;
}

class FontSystem extends UI {
  constructor(options = {}) {
super(options);
  }

  loadFont(callback = () => {}) {
    const self = this;
    const loader = new FontLoader();
    loader.load('./static/fonts/' + fontName + '_' + fontWeight + '.typeface.json', function(response) {
      const Font = response;
      callback(Font);
    });
  }
  loadTTF(options, callback = () => {}) {
    const self = this;
    /*
    ttf格式字体转换呢json
    */
    opentype.load(options.text.ttfUrl, function(err, font) {
      const loader = new FontLoader();
      var jsonFont = fontToThreeJSON(font);

      const Font = loader.parse(jsonFont);

      callback(Font)
    });
  }
}


export default FontSystem;